 package com.solution.admin.order.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.solution.admin.auth.service.RoleService;
import com.solution.admin.order.constants.OrderConstants;
import com.solution.admin.order.entity.OrderDetailEntity;
import com.solution.admin.order.entity.OrderEntity;
import com.solution.admin.order.entity.OrderInvoiceEntity;
import com.solution.admin.order.entity.OrderLogEntity;
import com.solution.admin.order.entity.OrderPayEntity;
import com.solution.admin.order.entity.OrderStatisticsEntity;
import com.solution.admin.order.service.OrderInvoiceService;
import com.solution.admin.order.service.OrderPayService;
import com.solution.admin.order.service.OrderService;
import com.solution.admin.product.entity.ProductSpecEntity;
import com.solution.admin.settings.entity.KeyMapEntity;
import com.solution.admin.settings.service.KeyMapService;
import com.solution.common.constants.PublicStatus;
import com.solution.common.controller.BaseController;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.JSONGridForOrder;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.DateUtils_add;
import com.solution.common.utils.string.StringUtil;

/**
 * 订单信息web控制层
 * @author lilp
 * @date 2017-09-14 23:35:39
 */
@RequestMapping("/order")
@Controller
public class OrderController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(OrderController.class);

	@Autowired
	private OrderService orderService;
	
	@Autowired
	private OrderPayService orderPayService;
	
	@Autowired
	private OrderInvoiceService orderInvoiceService;
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private KeyMapService keyMapService;
	
	/**
	 * 跳转订单信息查询页面
	 * @param Order 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toListOrderPage")
	public String toListOrderPage(OrderEntity order, HttpServletRequest request) {
		// 默认不是销售员
		request.setAttribute("isSalesman", 0);
		// 销售员的角色ID
		List<KeyMapEntity> keyList = keyMapService.listKeyMap("salesmanRoleId");
		if (null != keyList && keyList.size() > 0) {
			Long salesmanRoleId = Long.parseLong(keyList.get(0).getKeyValue());
			if (roleService.checkUserRoleChkFlg(getUserId(), salesmanRoleId)) {
				// 是销售员
				request.setAttribute("isSalesman", 1);
			}
		}
		return "order/order_list";
	}
	
	
	/**
	 * 跳转待付款订单查询页面
	 * @param Order 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toListToPayOrderPage")
	public String toListToPayOrderPage(OrderEntity order, HttpServletRequest request) {
		request.setAttribute("orderStatus", request.getParameter("orderStatus"));
		return "order/order_to_pay_list";
	}
	
	/**
	 * 跳转待审核订单查询页面
	 * @param Order 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toListToApproveOrderPage")
	public String toListToApproveOrderPage(OrderEntity order, HttpServletRequest request) {
		request.setAttribute("orderStatus", request.getParameter("orderStatus"));
		return "order/order_to_approve_list";
	}
	
	/**
	 * 跳转待发货订单查询页面
	 * @param Order 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toListToSendOrderPage")
	public String toListToSendOrderPage(OrderEntity order, HttpServletRequest request) {
		request.setAttribute("orderStatus", request.getParameter("orderStatus"));
		return "order/order_to_send_list";
	}
	
	
	/**
	 * 跳转待签收订单查询页面
	 * @param Order 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toListToSignOrderPage")
	public String toListToSignOrderPage(OrderEntity order, HttpServletRequest request) {
		request.setAttribute("orderStatus", request.getParameter("orderStatus"));
		return "order/order_to_sign_list";
	}
	
	/**
	 * 跳转到订单核销列表
	 * @param order
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年12月23日 上午9:51:41
	 */
	@RequestMapping("/toListVerifyOrderPage")
	public String toListVerifyOrderPage(OrderEntity order, HttpServletRequest request) {
		request.setAttribute("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_CHECK.getCode());
		request.setAttribute("payModel", "02");
		request.setAttribute("payStatus", OrderConstants.ORDER_PAY_CONFIRM_STATUS.CONFIRMED.getCode());
		return "order/order_to_verify_list";
	}
	
	/**
	 * （全部签收）签收订单
	 * @param order
	 * @param request
	 * @return
	 */
	@RequestMapping("signFullOrder")
	@ResponseBody
	public Map<String, String> signFullOrder(OrderEntity order, HttpServletRequest request) {
		Map<String, String> resultMap = new HashMap<String, String>();
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("orderCode", request.getParameter("orderCode"));
		param.put("creater", getUserName());
		//记录日志
		OrderLogEntity orderLog = new OrderLogEntity();
		orderLog.setOrderCode(request.getParameter("orderCode"));
		orderLog.setOperaterCode(getUserCode());
		orderLog.setOperaterName(getUserName());
		orderLog.setOpTime(new Date());
//		orderLog.setLogType(logType);
		orderLog.setLogContent("订单已签收");
		orderLog.setCreater(getUserName());
		param.put("orderLogEntity", orderLog);
		
		int result = 0;
		try {
			result = orderService.signFullOrder(param);
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
			resultMap.put(PublicStatus.RESULT_MSG, result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			handleException("订单全部签收失败", logger, e);
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
		}
		return resultMap;
	}
	
	
	/**
	 * 跳转已完成订单查询页面
	 * @param Order 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toListFinishedOrderPage")
	public String toListFinishedOrderPage(OrderEntity order, HttpServletRequest request) {
		request.setAttribute("orderStatus", request.getParameter("orderStatus"));
		return "order/order_finished_list";
	}
	
	
	/**
	 * 跳转待确认付款列表页面
	 * @param Order 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toListConfirmPayOrderPage")
	public String toListConfirmPayOrderPage(HttpServletRequest request) {
		request.setAttribute("orderStatus", request.getParameter("orderStatus"));
		return "order/order_confirm_pay_list";
	}
	
	/**
	 * 跳转至订单取消页面
	 * @param order
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年3月10日 下午1:42:10
	 */
	@RequestMapping("/toListCanceledOrderPage")
	public String toListCanceledOrderPage(OrderEntity order, HttpServletRequest request) {
		request.setAttribute("orderStatus", request.getParameter("orderStatus"));
		return "order/order_cancel_list";
	}
	
	
	/**
	 * 跳转订单审核页面
	 * @param Order 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toApproveOrder")
	public String toApproveOrder(OrderEntity order, HttpServletRequest request) {
		request.setAttribute("orderCode", request.getParameter("orderCode"));
		// 1 - 确认合同  2 确认付款凭证（详情页面确认）  
		//             21- 付款凭证列表页面，直接按钮确认
		//             22- 付款凭证详情页面确认
		request.setAttribute("confirmType", request.getParameter("confirmType"));
		return "order/order_approve_form";
	}
	
	/**
	 * 跳转订单（全部）发货页面
	 * @param Order 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toSendFullOrder")
	public String toSendFullOrder(OrderEntity order, HttpServletRequest request) {
		request.setAttribute("orderCode", request.getParameter("orderCode"));
		return "order/order_full_send_form";
	}
	
	/**
	 * 跳转订单（部分）发货页面
	 * @param Order 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toSendPartOrder")
	public String toSendPartOrder(OrderEntity order, HttpServletRequest request) {
		request.setAttribute("orderCode", request.getParameter("orderCode"));
		request.setAttribute("ids", request.getParameter("ids"));
		request.setAttribute("sendNum", request.getParameter("sendNum"));
		request.setAttribute("detailIds", request.getParameter("detailIds"));
		return "order/order_part_send_form";
	}
	

	/**
	 * 分页查询订单信息列表
	 * @param order 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/listOrderPage")
	@ResponseBody
	public JSONGrid listOrderPage(HttpServletRequest request){
		int pageNum=Integer.parseInt(request.getParameter("page").toString());
		int numPerPage=Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		// 时间区间类型
		String timeType = request.getParameter("timeType");
		String[] dates = DateUtils_add.getDateBetween(timeType);
		// 下单时间
		String orderTime = request.getParameter("orderTime");
		if (StringUtil.isNotNull(orderTime) && StringUtil.isEmpty(timeType) && orderTime.indexOf(" - ") > 0) {
			String[] orderTimeArr = orderTime.split(" - ");
			dates = orderTimeArr;
		}
		// 查询字符串
		String searchKey = request.getParameter("searchKey");
		// 订单状态
		String orderStatus = request.getParameter("orderStatus");
		// 支付模式
		String payModel = request.getParameter("payModel");
		// 支付状态
		String payStatus = request.getParameter("payStatus");
		// 运费调整状态
		String adjustPriceFlag = request.getParameter("adjustPriceFlag");
		// 订单编号
		String orderCode = request.getParameter("orderCode");
		// 客户名称
		String customerName = request.getParameter("customerName");
		// 客户电话
		String customerMobile = request.getParameter("customerMobile");
		// 客户单位
		String customerCompanyName = request.getParameter("customerCompanyName");
		String customerCompanyId = request.getParameter("customerCompanyId");
		// 业务员
		String salesmanName = request.getParameter("salesmanName");
		
		// 订单状态
		String searchOrderStatus = request.getParameter("searchOrderStatus");
		if(StringUtil.isNotEmpty(orderStatus)){
			searchOrderStatus = null;
		}else{
			orderStatus = searchOrderStatus;
		}
		// 业务员编号
		String salesmanCode = request.getParameter("salesmanCode");
		// 客户级别
		String customerLevel = request.getParameter("customerLevel");
		// 订单是否使用积分
		String usePointFlag = request.getParameter("usePointFlag");
		// 订单是否使用优惠券
		String useCouponFlag = request.getParameter("useCouponFlag");
		// 商品名称 
		String productName = request.getParameter("productName");
		// 商品类型
		String productCategoryId = request.getParameter("productCategoryId");
		// 商品品牌
		String productBrandCode = request.getParameter("productBrandCode");
		
		
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		
		paramMap.put("userId", getUserId());
		paramMap.put("salesmanFlag", getUserAuthType());
		// 超级管理员查看所有
		List<KeyMapEntity> keyList = keyMapService.listKeyMap("adminRoleId");
		if (null != keyList && keyList.size() > 0) {
			Long adminRoleId = Long.parseLong(keyList.get(0).getKeyValue());
			if (roleService.checkUserRoleChkFlg(getUserId(), adminRoleId)) {
				// 是超级管理员
				paramMap.remove("salesmanFlag");
				paramMap.remove("userId");
			}
		}
		
		keyList = keyMapService.listKeyMap("businessRoleId");
		if (null != keyList && keyList.size() > 0) {
			Long adminRoleId = Long.parseLong(keyList.get(0).getKeyValue());
			if (roleService.checkUserRoleChkFlg(getUserId(), adminRoleId)) {
				// 是超级管理员
				paramMap.remove("salesmanFlag");
				paramMap.remove("userId");
			}
		}
		
		//查询模式1(只使用searchKey查询)
		paramMap.put("searchKey", searchKey);
		//查询模式2(使用多条件查询)
		paramMap.put("orderCode", orderCode);
		paramMap.put("customerName", customerName);
		paramMap.put("customerMobile", customerMobile);
		paramMap.put("customerCompanyName", customerCompanyName);
		paramMap.put("customerCompanyId", customerCompanyId);
		paramMap.put("salesmanName", salesmanName);
		paramMap.put("orderStatus", orderStatus);
		
		paramMap.put("salesmanCode", salesmanCode);
		paramMap.put("customerLevel", customerLevel);
		paramMap.put("usePointFlag", usePointFlag);
		paramMap.put("useCouponFlag", useCouponFlag);
		paramMap.put("productName", productName);
		paramMap.put("productBrandCode", productBrandCode);
		paramMap.put("productCategoryId", productCategoryId);

		if(StringUtil.isNotNull(dates[0]) && StringUtil.isNotNull(dates[1])) {
			paramMap.put("startOrderTime", dates[0] + " 00:00:00");
			paramMap.put("endOrderTime", dates[1] + " 23:59:59");
		}
		paramMap.put("payModel", payModel);
		paramMap.put("payStatus", payStatus);
		paramMap.put("adjustPriceFlag", adjustPriceFlag);
		try {
			PageBean pageBean = orderService.listOrderPage(pageParam, paramMap);
			// 查询订单数量及金额统计
			OrderStatisticsEntity orderStat = orderService.selectOrderStatistics(paramMap);
			if(orderStat == null ){
				orderStat = new OrderStatisticsEntity(0, new BigDecimal(0));
			}
			List<Object> orderList = pageBean.getRecordList();
			// 处理商品详情数据的转化
			if(orderList != null && orderList.size() > 0){
				for (Object object : orderList) {
					OrderEntity order = (OrderEntity)object;
					String productDetail = order.getProductDetail();
					if(StringUtil.isNotEmpty(productDetail)){
						// 将商品详情json串转化为 OrderDetailEntity 列表
						String productDetailJsonStr = "["+productDetail+"]";
						List<OrderDetailEntity> orderDetailList = JSONArray.parseArray(productDetailJsonStr, OrderDetailEntity.class);
						order.setProductList(orderDetailList);
						
						if(orderDetailList != null && orderDetailList.size() > 0){
							for (OrderDetailEntity detail : orderDetailList) {
								if(StringUtil.isNotEmpty(detail.getProductSpec())){
									List<ProductSpecEntity> productSpecList = JSONArray.parseArray(detail.getProductSpec(), ProductSpecEntity.class);;
									detail.setProductSpecList(productSpecList);
									if(detail.getSendNum() > 0){
										order.setShowSign("true");
									}
								}
							}
						}
					}
				}
			}
			return new JSONGridForOrder(orderList,pageBean.getTotalCount(), orderStat.getOrderNum(), orderStat.getOrderMoney());
		} catch (Exception e) {
			handleException("分页查询订单信息失败", logger, e);
		}
		return new JSONGrid();
	}
	
	
	
	/**
	 * 分页查询订单发货单信息列表
	 * @param order 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/listOrderDeliveryBillPage")
	@ResponseBody
	public JSONGrid listOrderDeliveryBillPage(HttpServletRequest request){
		int pageNum=Integer.parseInt(request.getParameter("page").toString());
		int numPerPage=Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		
		//时间区间类型
		String timeType = request.getParameter("timeType");
		String[] dates = DateUtils_add.getDateBetween(timeType);
		// 下单时间
		String orderTime = request.getParameter("orderTime");
		if (StringUtil.isNotNull(orderTime) && StringUtil.isEmpty(timeType) && orderTime.indexOf(" - ") > 0) {
			String[] orderTimeArr = orderTime.split(" - ");
			dates = orderTimeArr;
		}
		// 查询字符串
		String searchKey = request.getParameter("searchKey");
		// 订单状态
		String orderStatus = request.getParameter("orderStatus");
		// 订单编号
		String orderCode = request.getParameter("orderCode");
		// 客户名称
		String customerName = request.getParameter("customerName");
		// 客户电话
		String customerMobile = request.getParameter("customerMobile");
		// 客户单位
		String customerCompanyName = request.getParameter("customerCompanyName");
		// 业务员
		String salesmanName = request.getParameter("salesmanName");
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userId", getUserId());
		paramMap.put("salesmanFlag", getUserAuthType());
		// 超级管理员查看所有
		List<KeyMapEntity> keyList = keyMapService.listKeyMap("adminRoleId");
		if (null != keyList && keyList.size() > 0) {
			Long adminRoleId = Long.parseLong(keyList.get(0).getKeyValue());
			if (roleService.checkUserRoleChkFlg(getUserId(), adminRoleId)) {
				// 是超级管理员
				paramMap.remove("salesmanFlag");
				paramMap.remove("userId");
			}
		}
		//查询模式1(只使用searchKey查询)
		paramMap.put("searchKey", searchKey);
		//查询模式2(使用多条件查询)
		paramMap.put("orderCode", orderCode);
		paramMap.put("customerName", customerName);
		paramMap.put("customerMobile", customerMobile);
		paramMap.put("customerCompanyName", customerCompanyName);
		paramMap.put("salesmanName", salesmanName);
		
		paramMap.put("orderStatus", orderStatus);
//		paramMap.put("startOrderTime", dates[0]);
//		paramMap.put("endOrderTime", dates[1]);
		if(StringUtil.isNotNull(dates[0]) && StringUtil.isNotNull(dates[1])) {
			paramMap.put("startOrderTime", dates[0] + " 00:00:00");
			paramMap.put("endOrderTime", dates[1] + " 23:59:59");
		}
		try {
			PageBean pageBean = orderService.listOrderDeliveryBillPage(pageParam, paramMap);
			
			List<Object> orderList = pageBean.getRecordList();
			// 处理商品详情数据的转化
			if(orderList != null && orderList.size() > 0){
				for (Object object : orderList) {
					OrderEntity order = (OrderEntity)object;
					String productDetail = order.getProductDetail();
					if(StringUtil.isNotEmpty(productDetail)){
						// 将商品详情json串转化为 OrderDetailEntity 列表
						String productDetailJsonStr = "["+productDetail+"]";
						List<OrderDetailEntity> orderDetailList = JSONArray.parseArray(productDetailJsonStr, OrderDetailEntity.class);
						order.setProductList(orderDetailList);
						
						if(orderDetailList != null && orderDetailList.size() > 0){
							for (OrderDetailEntity detail : orderDetailList) {
								if(StringUtil.isNotEmpty(detail.getProductSpec())){
									List<ProductSpecEntity> productSpecList = JSONArray.parseArray(detail.getProductSpec(), ProductSpecEntity.class);;
									detail.setProductSpecList(productSpecList);
								}
							}
						}
					}
				}
			}
			return new JSONGrid(orderList,pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询订单发货单信息失败", logger, e);
		}
		return new JSONGrid();
	}
	
	
	/**
	 * 分页查询待确认的付款凭证（列表关联显示订单单信)
	 * @param order 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/listConformPayOrderPage")
	@ResponseBody
	public JSONGrid listConformPayOrderPage(HttpServletRequest request){
		int pageNum=Integer.parseInt(request.getParameter("page").toString());
		int numPerPage=Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		
		// 时间区间类型
		String timeType = request.getParameter("timeType");
		String[] dates = DateUtils_add.getDateBetween(timeType);
		// 下单时间
		String orderTime = request.getParameter("orderTime");
		if (StringUtil.isNotNull(orderTime) && StringUtil.isEmpty(timeType) && orderTime.indexOf(" - ") > 0) {
			String[] orderTimeArr = orderTime.split(" - ");
			dates = orderTimeArr;
		}
		// 查询字符串
		String searchKey = request.getParameter("searchKey");
		// 订单状态
		String orderStatus = request.getParameter("orderStatus");
		// 支付类型 
		String payType = request.getParameter("payType");
		// 支付模式
		String payModel = request.getParameter("payModel");
		// 订单编号
		String orderCode = request.getParameter("orderCode");
		// 客户名称
		String customerName = request.getParameter("customerName");
		// 客户电话
		String customerMobile = request.getParameter("customerMobile");
		// 客户单位
		String customerCompanyName = request.getParameter("customerCompanyName");
		// 业务员
		String salesmanName = request.getParameter("salesmanName");
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userId", getUserId());
		paramMap.put("salesmanFlag", getUserAuthType());
		// 超级管理员查看所有
		List<KeyMapEntity> keyList = keyMapService.listKeyMap("adminRoleId");
		if (null != keyList && keyList.size() > 0) {
			Long adminRoleId = Long.parseLong(keyList.get(0).getKeyValue());
			if (roleService.checkUserRoleChkFlg(getUserId(), adminRoleId)) {
				// 是超级管理员
				paramMap.remove("salesmanFlag");
				paramMap.remove("userId");
			}
		}
		//查询模式1(只使用searchKey查询)
		paramMap.put("searchKey", searchKey);
		//查询模式2(使用多条件查询)
		paramMap.put("orderCode", orderCode);
		paramMap.put("customerName", customerName);
		paramMap.put("customerMobile", customerMobile);
		paramMap.put("customerCompanyName", customerCompanyName);
		paramMap.put("salesmanName", salesmanName);
		
		paramMap.put("orderStatus", orderStatus);
//		paramMap.put("startOrderTime", dates[0]);
//		paramMap.put("endOrderTime", dates[1]);
		if(StringUtil.isNotNull(dates[0]) && StringUtil.isNotNull(dates[1])) {
			paramMap.put("startOrderTime", dates[0] + " 00:00:00");
			paramMap.put("endOrderTime", dates[1] + " 23:59:59");
		}
		paramMap.put("payType", payType);
		paramMap.put("payModel", payModel);
		try {
			PageBean pageBean = orderService.listConfirmPayOrderPage(pageParam, paramMap);
			
			List<Object> orderList = pageBean.getRecordList();
			// 处理商品详情数据的转化
			if(orderList != null && orderList.size() > 0){
				for (Object object : orderList) {
					OrderEntity order = (OrderEntity)object;
					String productDetail = order.getProductDetail();
					if(StringUtil.isNotEmpty(productDetail)){
						// 将商品详情json串转化为 OrderDetailEntity 列表
						String productDetailJsonStr = "["+productDetail+"]";
						List<OrderDetailEntity> orderDetailList = JSONArray.parseArray(productDetailJsonStr, OrderDetailEntity.class);
						order.setProductList(orderDetailList);
					
						if(orderDetailList != null && orderDetailList.size() > 0){
							for (OrderDetailEntity detail : orderDetailList) {
								if(StringUtil.isNotEmpty(detail.getProductSpec())){
									List<ProductSpecEntity> productSpecList = JSONArray.parseArray(detail.getProductSpec(), ProductSpecEntity.class);;
									detail.setProductSpecList(productSpecList);
								}
							}
						}
					}
				}
			}
			return new JSONGrid(orderList,pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询待确认的付款凭证列表错误", logger, e);
		}
		return new JSONGrid();
	}
	
	
	
	/**
	 * 导出订单
	 * @param request
	 */
	@RequestMapping("/exportOrder")
	public void exportOrder(HttpServletRequest request, HttpServletResponse response){
		// 时间区间类型
		String timeType = request.getParameter("timeType");
		String[] dates = DateUtils_add.getDateBetween(timeType);
		// 使用下单时间区间自定义查询
		String orderTime = request.getParameter("orderTime");
		if (StringUtil.isNotNull(orderTime) && StringUtil.isEmpty(timeType) && orderTime.indexOf(" - ") > 0) {
			String[] orderTimeArr = orderTime.split(" - ");
			dates = orderTimeArr;
		}
		// 查询字符串
		String searchKey = request.getParameter("searchKey");
		// 订单状态
		String orderStatus = request.getParameter("orderStatus");
		// 支付模式
		String payModel = request.getParameter("payModel");
		// 支付状态
		String payStatus = request.getParameter("payStatus");
		// 订单编号
		String orderCode = request.getParameter("orderCode");
		// 客户名称
		String customerName = request.getParameter("customerName");
		// 客户电话
		String customerMobile = request.getParameter("customerMobile");
		// 客户单位
		String customerCompanyName = request.getParameter("customerCompanyName");
		// 业务员
		String salesmanName = request.getParameter("salesmanName");
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userId", getUserId());
		paramMap.put("salesmanFlag", getUserAuthType());
		// 超级管理员查看所有
		List<KeyMapEntity> keyList = keyMapService.listKeyMap("adminRoleId");
		if (null != keyList && keyList.size() > 0) {
			Long adminRoleId = Long.parseLong(keyList.get(0).getKeyValue());
			if (roleService.checkUserRoleChkFlg(getUserId(), adminRoleId)) {
				// 是超级管理员
				paramMap.remove("salesmanFlag");
				paramMap.remove("userId");
			}
		}
		//查询模式1(只使用searchKey查询)
		paramMap.put("searchKey", searchKey);
		//查询模式2(使用多条件查询)
		paramMap.put("orderCode", orderCode);
		paramMap.put("customerName", customerName);
		paramMap.put("customerMobile", customerMobile);
		paramMap.put("customerCompanyName", customerCompanyName);
		paramMap.put("salesmanName", salesmanName);
		
		paramMap.put("orderStatus", orderStatus);
		paramMap.put("payModel", payModel);
		paramMap.put("payStatus", payStatus);
//		paramMap.put("startOrderTime", dates[0]);
//		paramMap.put("endOrderTime", dates[1]);
		if(StringUtil.isNotNull(dates[0]) && StringUtil.isNotNull(dates[1])) {
			paramMap.put("startOrderTime", dates[0] + " 00:00:00");
			paramMap.put("endOrderTime", dates[1] + " 23:59:59");
		}
		try {
			List<OrderEntity> orderList = orderService.listOrder(paramMap);
			List<String> headNames = new ArrayList<String>();
			headNames.add("订单编号");
			headNames.add("下单时间");
			headNames.add("客户名称");
			headNames.add("客户电话");
			headNames.add("客户公司");
			headNames.add("订单金额");
			headNames.add("应付金额");
			headNames.add("商品调价金额合计");
			headNames.add("订单金额调价");
			headNames.add("运费");
			headNames.add("活动折扣金额");
			headNames.add("优惠券抵扣金额");
			headNames.add("积分抵扣金额");
			headNames.add("订单状态");
			headNames.add("支付模式");
			headNames.add("支付方式");
			headNames.add("快递方式");
			headNames.add("收货人");
			headNames.add("收货人电话");
			headNames.add("收货省");
			headNames.add("收货市");
			headNames.add("收货区");
			headNames.add("收货街道");
			headNames.add("收货详细地址");
			headNames.add("开票类型");
			
			List<String> fieldNames = new ArrayList<String>();
			fieldNames.add("orderCode");
			fieldNames.add("orderTimeStr");
			fieldNames.add("customerName");
			fieldNames.add("customerMobile");
			fieldNames.add("customerCompanyName");
			fieldNames.add("orderMoney");
			fieldNames.add("realPayMoney");
			fieldNames.add("adjustProductMoney");
			fieldNames.add("adjustOrderMoney");
			fieldNames.add("deliveryFeeMoney");
			fieldNames.add("promotionDiscountMoney");
			fieldNames.add("couponMoney");
			fieldNames.add("pointsMoney");
			fieldNames.add("orderStatusName");
			fieldNames.add("payModelName");
			fieldNames.add("payTypeName");
			fieldNames.add("deliveryTypeName");
			fieldNames.add("receiverName");
			fieldNames.add("receiverMobile");
			fieldNames.add("provinceName");
			fieldNames.add("cityName");
			fieldNames.add("areaName");
			fieldNames.add("streetName");
			fieldNames.add("address");
			fieldNames.add("invoiceTypeName");
			
			expToExcel07(request, response, headNames, fieldNames, "OrderInfo.xlsx", orderList);
		} catch (Exception e) {
			handleException("分页查询订单信息失败", logger, e);
		}
	}
	
	/**
	 * 跳转订单打印页面
	 * @param order
	 * @param request
	 * @return
	 */
	@RequestMapping("/toPrintOrder")
	public String toPrintOrder( HttpServletRequest request) {
		
		// 由于订单全部订单、待支付订单、待审核订单、待发货订单列表页面都有打印按钮，公用同一个打印页面
		// 在此做标记是由哪个列表页面进入的打印页面，用于返回按钮，返回到对应列表
		// 01 -全部订单 02-待支付  03-待审核  04 -待发货 
		String fromPage = request.getParameter("fromPage");
		request.setAttribute("fromPage", fromPage);
		
		// 订单编号
		String orderCode = request.getParameter("orderCode");
		request.setAttribute("orderCode", orderCode);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderCode", orderCode);
		try {
			// 查询单条订单
			List<OrderEntity> orderList = orderService.listOrder(paramMap);
			if (orderList != null && orderList.size() > 0) {
				OrderEntity order = orderList.get(0);
				if (StringUtil.isNotEmpty(order.getProductDetail())) {
					List<OrderDetailEntity> productList = JSONArray.parseArray(
							"[" + order.getProductDetail() + "]",
							OrderDetailEntity.class);
					if (productList != null && productList.size() > 0) {
						for (OrderDetailEntity product : productList) {
							// 累计商品总金额 如果有商品调价，则按调价后价格，否则按商品原价
							product.setProductItemMoney((
											product.getProductAdjustPrice() == null ? 
											product.getProductPrice() : 
											product.getProductAdjustPrice())
									.multiply(new BigDecimal(product.getBuyNum())));
						}
					}
					request.setAttribute("productList", productList);
				}
				request.setAttribute("order", order);
			}
		} catch (Exception e) {
			handleException("跳转订单详情页面", logger, e);
		}
		return "order/order_print";
	}
	
	/**
	 * 跳转到订单调价页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/toAdjustOrderProductPrice")
	public String listOrderDetailByOrderCode(HttpServletRequest request){
		// 订单编号 
		String orderCode = request.getParameter("orderCode");
		request.setAttribute("orderCode", orderCode);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderCode", orderCode);
		try {
			// 查询单条订单
			List<OrderEntity> orderList = orderService.listOrder(paramMap);
			if(orderList !=null && orderList.size() > 0){
				// 商品原价总金额
				BigDecimal totalProductMoney = new BigDecimal(0);
				OrderEntity order = orderList.get(0);
				if(StringUtil.isNotEmpty(order.getProductDetail())){
					List<OrderDetailEntity> productList = JSONArray.parseArray("["+order.getProductDetail()+"]",OrderDetailEntity.class);
					// 单品调价总计
					BigDecimal totalDiffMoney = new BigDecimal(0);
					if(productList != null && productList.size() > 0 ){
						for (OrderDetailEntity product : productList) {
							// 累计商品总金额 如果有商品调价，则按调价后价格，否则按商品原价计算
							BigDecimal itemMoney = product.getProductAdjustPrice().multiply(new BigDecimal(product.getBuyNum()));
							product.setSubTotalItemMoney(itemMoney);
							totalProductMoney = totalProductMoney.add(itemMoney);
							totalDiffMoney = totalDiffMoney.add((product.getProductPrice().subtract(product.getProductAdjustPrice()).multiply(new BigDecimal(product.getBuyNum()))));
						}
						request.setAttribute("totalDiffMoney", totalDiffMoney);
					}
				}
				request.setAttribute("totalProductMoney", totalProductMoney);
				request.setAttribute("order", order);
			}
		} catch (Exception e) {
			handleException("跳转到订单调价页面", logger, e);
		}
		return "/order/order_adjust_price";
	}
	
	

	/**
	 * 跳转订单详情页面
	 * @return string 跳转页面路径
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toOrderDetail")
	public String toOrderDetail(HttpServletRequest request) {
		// 默认选择tabIndex
		request.setAttribute("tabIndex", request.getParameter("tabIndex"));
		// 订单编号
		String orderCode = request.getParameter("orderCode");
		request.setAttribute("orderCode", orderCode);
		request.setAttribute("date", new Date().getTime());
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderCode", orderCode);
		try {
			// 查询单条订单
			List<OrderEntity> orderList = orderService.listOrder(paramMap);
			if (orderList != null && orderList.size() > 0) {
				OrderEntity order = orderList.get(0);
				if (StringUtil.isNotEmpty(order.getProductDetail())) {
					List<OrderDetailEntity> productList = JSONArray.parseArray(
							"[" + order.getProductDetail() + "]",
							OrderDetailEntity.class);
					if (productList != null && productList.size() > 0) {
						for (OrderDetailEntity product : productList) {
							// 累计商品总金额 如果有商品调价，则按调价后价格，否则按商品原价
							product.setProductItemMoney(
									(product.getProductAdjustPrice().equals(product.getProductPrice())? product.getProductPrice() : product.getProductAdjustPrice())
									.multiply(new BigDecimal(product.getBuyNum())));
						
							if(StringUtil.isNotEmpty(product.getProductSpec())){
								List<ProductSpecEntity> productSpecList = JSONArray.parseArray(product.getProductSpec(), ProductSpecEntity.class);;
								product.setProductSpecList(productSpecList);
							}
						}
					}
					request.setAttribute("productList", productList);
					order.setProductList(productList);
				}
				request.setAttribute("order", order);
				// 查询发票信息
				List<OrderInvoiceEntity>  invoiceList = orderInvoiceService.listOrderInvoice(paramMap);
				if(invoiceList != null && invoiceList.size() > 0){
					request.setAttribute("invoice", invoiceList.get(0));
				}
			}
			Long salesmanRoleId = null;
			// 默认不是销售员
			request.setAttribute("isSalesman", 0);
			// 销售员的角色ID
			List<KeyMapEntity> keyList = keyMapService.listKeyMap("salesmanRoleId");
			if (null != keyList && keyList.size() > 0) {
				salesmanRoleId = Long.parseLong(keyList.get(0).getKeyValue());
				if (roleService.checkUserRoleChkFlg(getUserId(), salesmanRoleId)) {
					// 是销售员
					request.setAttribute("isSalesman", 1);
				}
			}
		} catch (Exception e) {
			handleException("跳转订单详情页面", logger, e);
		}
		return "order/order_form";
	}
	
	/**
	 * 跳转订单付款凭证详情页面
	 * @return string 跳转页面路径
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/toOrderPayDetail")
	public String toOrderPayDetail(HttpServletRequest request) {
		// 订单编号
		String orderCode = request.getParameter("orderCode");
		request.setAttribute("orderCode", orderCode);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderCode", orderCode);
		try {
			// 查询单条订单
			List<OrderEntity> orderList = orderService.listOrder(paramMap);
			if (orderList != null && orderList.size() > 0) {
				OrderEntity order = orderList.get(0);
				request.setAttribute("order", order);
			}
			
			// 查询订单付款凭证
			List<OrderPayEntity>  payList = orderPayService.listOrderPay(paramMap);
			if(payList != null && payList.size() > 0){
				request.setAttribute("payList", payList);
			}
		} catch (Exception e) {
			handleException("跳转订单详情页面", logger, e);
		}
		return "order/order_confirm_pay";
	}


	/**
	 * 新增或保存订单信息
	 * @param request 请求对象
	 * @param orderEntity 订单信息实体
	 * @return
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/saveOrUpdateOrder")
	@ResponseBody
	public Map<String, Object> saveOrder(HttpServletRequest request, OrderEntity orderEntity) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		try {
			String id = request.getParameter("id");
			if(StringUtil.isEmpty(id)){
				result = orderService.updateOrder(orderEntity);
			}else{
				result = (int)orderService.saveOrder(orderEntity);
			}
			resultMap.put("code", result);
		} catch (Exception e) {
			handleException("添加订单信息失败", logger, e);
		}
		return resultMap;
	}
	
	
	/**
	 * 订单调价操作
	 * @param request 请求对象
	 * @param orderEntity 订单信息实体
	 * @return
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/adjustOrderPrice")
	@ResponseBody
	public Map<String, Object> adjustOrderPrice(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		Map<String, Object> param = new HashMap<String, Object>();
		String orderCode = request.getParameter("orderCode");
		String ids = request.getParameter("ids");
		// 每个商品调价值，以,号隔开的字符串  
		String produtAdjustPrice = request.getParameter("produtAdjustPrice");
		String produtPrice = request.getParameter("produtPrice");
		
		// 对应每个商品购物数量，以,号隔开的字符串
		String buyNums = request.getParameter("buyNums");
		String deliveryFeeMoney = request.getParameter("deliveryFeeMoney");
		String orderAdjustMoney = request.getParameter("orderAdjustMoney");
		
		param.put("orderCode", orderCode);
		param.put("ids", ids);
		param.put("produtAdjustPrice", produtAdjustPrice);
		param.put("produtPrice", produtPrice);
		param.put("buyNums", buyNums);
		param.put("deliveryFeeMoney", deliveryFeeMoney);
		param.put("orderAdjustMoney", orderAdjustMoney);
		try {
			result = orderService.adjustOrderPrice(param);
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
			resultMap.put(PublicStatus.RESULT_MSG, result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			handleException("订单调价操作失败", logger, e);
		}
		return resultMap;
	}
	
	

	/**
	 * 商务审核订单
	 * @param request 请求对象
	 * @param orderEntity 订单信息实体
	 * @return
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/approveOrder")
	@ResponseBody
	public Map<String, Object> approveOrder(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		Map<String, Object> param = new HashMap<String, Object>();
		// 1 确认合同   2 确认付款凭证
		String confirmType = request.getParameter("confirmType");
		// 订单号
		String orderCode = request.getParameter("orderCode");
		// 审批结果
		String approveResult = request.getParameter("approveResult");
		// 审批意见
		String approveReason = request.getParameter("approveReason");
		param.put("orderCode", orderCode);
		param.put("approveResult", approveResult);

		//记录日志
		OrderLogEntity orderLog = new OrderLogEntity();
		orderLog.setOrderCode(orderCode);
		orderLog.setOperaterCode(getUserCode());
		orderLog.setOperaterName(getUserName());
		orderLog.setOpTime(new Date());
//		orderLog.setLogType(logType);
		orderLog.setCreater(getUserName());
		
		if(OrderConstants.ORDER_APPROVE_STATUS.PASS.getCode().equals(approveResult)){
			// 待发货
			param.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_SEND.getCode());
			orderLog.setLogContent("审核订单通过");
		}else{
			// 审核驳回 ，订单进入前台进行调整，重新上传合同或添加支付凭证
			param.put("orderStatus", OrderConstants.ORDER_STATUS.APPROVE_REJECTED.getCode());
			if ("1".equals(confirmType)) {
				orderLog.setLogContent("审核驳回合同凭证；驳回原因："+approveReason);
			} else if ("2".equals(confirmType)) {
				orderLog.setLogContent("审核驳回付款凭证；驳回原因："+approveReason);
			} else {
				orderLog.setLogContent(approveReason);
			}
		}
		param.put("orderLogEntity", orderLog);
		param.put("approveReason", approveReason);
		param.put("approverCode", getUserCode());	//审核人
		param.put("approverName", getUserName());	//审批人姓名
		param.put("confirmType", confirmType);		//确认合同/付款凭证
		// 修改人
		param.put("modifier", getUserCode());

		// 前面根据判断类型，显示对应的tabIndex
		resultMap.put("confirmType", confirmType);
		try {
			result = orderService.approveOrder(param);
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
			resultMap.put(PublicStatus.RESULT_MSG, result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("商务审核订单", logger, e);
		}
		return resultMap;
	}
	
	/**
	 * 取消订单
	 * @param request 请求对象
	 * @param orderEntity 订单信息实体
	 * @return
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/cancelOrder")
	@ResponseBody
	public Map<String, Object> cancelOrder(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		Map<String, Object> param = new HashMap<String, Object>();
		// 订单号
		String orderCode = request.getParameter("orderCode");
		String cancelReason = request.getParameter("cancelReason");
		if (StringUtil.isEmpty(cancelReason)) {
			cancelReason = "后台人员"+getUserName()+"取消了订单";
		}
		param.put("orderCode", orderCode);
		param.put("orderStatus", OrderConstants.ORDER_STATUS.CANCELED.getCode());
		param.put("cancelReason", cancelReason);
		param.put("cancelIntro", request.getParameter("cancelIntro"));
		// 修改人
		param.put("modifier", getUserCode());
		try {
			result = orderService.cancelOrder(param);
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
			resultMap.put(PublicStatus.RESULT_MSG, result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("取消订单", logger, e);
		}
		return resultMap;
	}
	
	
	
	/**
	 * 确认合同
	 * @param request 请求对象
	 * @param orderEntity 订单信息实体
	 * @return
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/confirmOrderContract")
	@ResponseBody
	public Map<String, Object> confirmOrderContract(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		Map<String, Object> param = new HashMap<String, Object>();
		// 订单号
		String orderCode = request.getParameter("orderCode");
		param.put("orderCode", orderCode);
		// 确认合同后订单变成待发货状态
		param.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_SEND.getCode());
		// 合同已确认
		param.put("confirmStatus", OrderConstants.ORDER_CONTRACT_STATUS.CONFIRMED.getCode());
		// 修改人
		param.put("modifier", getUserCode());
		try {
			result = orderService.confirmOrderContract(param);
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
			resultMap.put(PublicStatus.RESULT_MSG, result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("取消订单", logger, e);
		}
		return resultMap;
	}
	
	
	/**
	 * 确认收货(后台人员代为签收订单)
	 * @param request 请求对象
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/confirmSign")
	@ResponseBody
	public Map<String, Object> confrimSign(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 订单号
		String orderCode = request.getParameter("orderCode");
		String deliveryCode = request.getParameter("deliveryCode");
		String deliveryBillId = request.getParameter("deliveryBillId");
		try {
			Map<String, Object> param = new HashMap<String , Object>();
			param.put("orderCode", orderCode);
			// 签收订单，检查是否发货完成，发货完成则修改订单状态 
			param.put("deliveryCode", deliveryCode);
			param.put("deliveryBillId", deliveryBillId);
			param.put("signTime", new Date());
			param.put("signStatus", OrderConstants.ORDER_SIGN_STATUS.SIGNED.getCode());
			param.put("signName", getUserName());
			param.put("modifier", getUserName());
			//记录日志
			OrderLogEntity orderLog = new OrderLogEntity();
			orderLog.setOrderCode(orderCode);
			orderLog.setOperaterCode(getUserCode());
			orderLog.setOperaterName(getUserName());
			orderLog.setOpTime(new Date());
//			orderLog.setLogType(logType);
			orderLog.setLogContent("订单已签收");
			orderLog.setCreater(getUserName());
			param.put("orderLogEntity", orderLog);
			// 签收部分发货单
			int result = orderService.signHalfOrder(param);
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
			resultMap.put(PublicStatus.RESULT_MSG, result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			handleException("取消订单错误", logger, e);
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
		}
		return resultMap;
	}

	/**
	 * 订单核销弹窗
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年1月22日 下午8:02:35
	 */
	@RequestMapping("/toVerifyOrder")
	public String toVerifyOrder(OrderEntity order, HttpServletRequest request) {
		request.setAttribute("orderCode", request.getParameter("orderCode"));
		request.setAttribute("confirmType", request.getParameter("confirmType"));
		return "order/order_verify_form";
	}
	
	/**
	 * 核销订单
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年12月23日 上午10:35:19
	 */
	@RequestMapping("/confirmVerifyOrder")
	@ResponseBody
	public Map<String, Object> confirmVerifyOrder(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		Map<String, Object> param = new HashMap<String, Object>();
		//2 确认付款凭证
		String confirmType = request.getParameter("confirmType");
		// 订单号
		String orderCode = request.getParameter("orderCode");
		// 审批结果
		String approveResult = request.getParameter("approveResult");
		// 审批意见
		String approveReason = request.getParameter("approveReason");
		param.put("orderCode", orderCode);
		param.put("approveResult", approveResult);
		//记录日志
		OrderLogEntity orderLog = new OrderLogEntity();
		orderLog.setOrderCode(orderCode);
		orderLog.setOperaterCode(getUserCode());
		orderLog.setOperaterName(getUserName());
		orderLog.setOpTime(new Date());
//		orderLog.setLogType(logType);
		orderLog.setCreater(getUserName());
		if(OrderConstants.ORDER_APPROVE_STATUS.PASS.getCode().equals(approveResult)){
			// 核销通过，订单完成
			param.put("orderStatus", OrderConstants.ORDER_STATUS.FINISHED.getCode());
			orderLog.setLogContent("订单已核销");
		}else{
			// 核销驳回，重新上传支付凭证
			param.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_PAY.getCode());
			param.put("payStatus", OrderConstants.ORDER_PAY_STATUS.NOT_PAY.getCode());
			orderLog.setLogContent("订单核销驳回；驳回原因："+approveReason);
		}
		param.put("orderLogEntity", orderLog);
		param.put("approveReason", approveReason);
		param.put("approverCode", getUserCode());	//审核人
		param.put("approverName", getUserName());	//审批人姓名
		param.put("confirmType", confirmType);		//确认合同/付款凭证
		// 修改人
		param.put("modifier", getUserCode());
		
		// 前面根据判断类型，显示对应的tabIndex
		resultMap.put("confirmType", confirmType);
		try {
			result = orderService.confirmVerifyOrder(param);
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
			resultMap.put(PublicStatus.RESULT_MSG, result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("商务核销订单", logger, e);
		}
		return resultMap;
	}
	
	/**
	 * 跳转至订单数据统计页面
	 * @param order
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年1月2日 下午4:08:34
	 */
	@RequestMapping("/toQueryOrderData")
	public String toQueryOrderData(OrderEntity order, HttpServletRequest request) {
		Map<String, Object> orderState = orderService.queryOrderStatusSum();
		request.setAttribute("orderState", orderState);
		return "order/order_data";
	}
	
	/**
	 * 查询订单统计数据
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年1月2日 下午4:10:12
	 */
	@RequestMapping("/queryOrderData")
	@ResponseBody
	public Map<String, Object> queryOrderData(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		
		String orderStatus = request.getParameter("orderStatus");
		String timeType = request.getParameter("timeType");
		String startTime = request.getParameter("startTime") + " 00:00:00";
		String endTime = request.getParameter("endTime") + " 23:59:59";
		if ("part".equals(timeType)) {
			paramMap.put("startOrderTime", startTime);
			paramMap.put("endOrderTime", endTime);
		} else {
			String[] dates = DateUtils_add.getDateBetween(timeType);
//			paramMap.put("startOrderTime", dates[0]);
//			paramMap.put("endOrderTime", dates[1]);
			if(StringUtil.isNotNull(dates[0]) && StringUtil.isNotNull(dates[1])) {
				paramMap.put("startOrderTime", dates[0] + " 00:00:00");
				paramMap.put("endOrderTime", dates[1] + " 23:59:59");
			}
		}
		paramMap.put("orderStatus", orderStatus);
		
		try {
			Map<String, Object> orderDataMap = orderService.queryOrderData(paramMap);
			String[] allDate = null;
			String[] allDateShow = null;
			if ("part".equals(timeType)) {
				allDate = DateUtils_add.getDateBetweenStartToEnd(startTime, endTime, "yyyy/MM/dd");
				allDateShow = DateUtils_add.getDateBetweenStartToEnd(startTime, endTime, "MM/dd");
			} else {
				allDate = DateUtils_add.getDateBetweenAll(timeType, "yyyy/MM/dd");
				allDateShow = DateUtils_add.getDateBetweenAll(timeType, "MM/dd");
			}
			
			List<String> orderMoneyValues = new ArrayList<String>();
			List<String> realPayMoneyValues = new ArrayList<String>();
			List<String> sumValues = new ArrayList<String>();
			for (int i=0; i<allDate.length; i++) {
				String date = allDate[i];
				if(orderDataMap.containsKey(date)){
					JSONObject json = JSON.parseObject(JSON.toJSONString(orderDataMap.get(date)));
					orderMoneyValues.add(json.getString("orderMoney"));
					realPayMoneyValues.add(json.getString("realPayMoney"));
					sumValues.add(json.getString("sum"));
				} else {
					//当天的数据还未统计,不在坐标上标识
//					if (i != (allDate.length-1)) {
						orderMoneyValues.add("0");
						realPayMoneyValues.add("0");
						sumValues.add("0");
//					}
				}
			}
			resultMap.put("allDate", allDate);
			resultMap.put("allDateShow", allDateShow);
			resultMap.put("orderMoneyValues", orderMoneyValues);
			resultMap.put("realPayMoneyValues", realPayMoneyValues);
			resultMap.put("sumValues", sumValues);
			resultMap.put(PublicStatus.RESULT_CODE, "1");
			resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("查询订单统计数据", logger, e);
		}
		return resultMap;
	}
	
	/**
	 * 导出订单
	 * @param request
	 */
	@RequestMapping("/exportOrderData")
	public void exportOrderData(HttpServletRequest request, HttpServletResponse response){
		//订单状态
		String orderStatus = request.getParameter("orderStatus");
		//订单状态名称
		String orderStatusName = request.getParameter("orderStatusName");
		//时间类型
		String timeType = request.getParameter("timeType");
		//起始时间
		String startTime = request.getParameter("startTime") + " 00:00:00";
		//结束时间
		String endTime = request.getParameter("endTime") + " 23:59:59";
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		if ("part".equals(timeType)) {
			paramMap.put("startOrderTime", startTime);
			paramMap.put("endOrderTime", endTime);
		} else {
			String[] dates = DateUtils_add.getDateBetween(timeType);
//			paramMap.put("startOrderTime", dates[0]);
//			paramMap.put("endOrderTime", dates[1]);
			if(StringUtil.isNotNull(dates[0]) && StringUtil.isNotNull(dates[1])) {
				paramMap.put("startOrderTime", dates[0] + " 00:00:00");
				paramMap.put("endOrderTime", dates[1] + " 23:59:59");
			}
		}
		paramMap.put("orderStatus", orderStatus);
		StringBuffer title = new StringBuffer();
		try {
			if (paramMap.containsKey("startOrderTime")) {
				title.append(paramMap.get("startOrderTime").toString().substring(0, 10));
			}
			if (paramMap.containsKey("endOrderTime")) {
				title.append("至");
				title.append(paramMap.get("endOrderTime").toString().substring(0, 10));
			}
			title.append(orderStatusName+"订单统计");
			List<Object> orderDataList = orderService.queryOrderDataList(paramMap);
			List<String> headNames = new ArrayList<String>();
			headNames.add("下单日期");
			headNames.add("下单数量");
			headNames.add("订单总金额");
			headNames.add("实付金额");
			
			List<String> fieldNames = new ArrayList<String>();
			fieldNames.add("orderTimeGroup");
			fieldNames.add("sum");
			fieldNames.add("orderMoney");
			fieldNames.add("realPayMoney");
			
			expToExcel07(request, response, headNames, fieldNames, title+".xlsx", orderDataList);
		} catch (Exception e) {
			handleException("导出"+title+"失败", logger, e);
		}
	}
}
